package cn.xu.sse;

import com.alibaba.fastjson.JSONObject;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;

/**
 * @Author xuguofei clark2021@qq.com || WX clark_2023
 * @Date 2024/5/22
 * @Desc
 **/
@RestController
public class SseTestController {

    @GetMapping(value = "/test",produces = MediaType.APPLICATION_JSON_VALUE)
    public String test(){
        return "{\"success\":true}";
    }

    @PostMapping(value = "/events", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter streamEvents(@RequestBody JSONObject jsonObject) {
        SseEmitter emitter = new SseEmitter(Long.MAX_VALUE); // 无限期保持连接，直到手动关闭

        // 使用一个线程模拟发送SSE事件
        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) { // 发送10个事件作为示例
                    emitter.send(i + " - This is an SSE event. "+jsonObject.toJSONString());
                    Thread.sleep(1000); // 发送间隔为1秒
                }
                emitter.complete(); // 发送完所有事件后关闭连接
            } catch (IOException | InterruptedException e) {
                emitter.completeWithError(e); // 发生异常时关闭连接并发送错误信息
            }
        }).start();

        return emitter;
    }
    @GetMapping(value = "/sse", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter sse() {
        SseEmitter emitter = new SseEmitter(Long.MAX_VALUE); // 无限期保持连接，直到手动关闭

        // 使用一个线程模拟发送SSE事件
        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) { // 发送10个事件作为示例
                    emitter.send(i + " - This is an SSE event. ");
                    Thread.sleep(1000); // 发送间隔为1秒
                }
                emitter.complete(); // 发送完所有事件后关闭连接
            } catch (IOException | InterruptedException e) {
                emitter.completeWithError(e); // 发生异常时关闭连接并发送错误信息
            }
        }).start();

        return emitter;
    }


}
